package com.ijmacd.footballtracker;

import java.io.IOException;
import java.net.URI;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.ijmacd.footballtracker.Provider.Matches;

import android.app.ListActivity;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;

public class MatchListActivity extends ListActivity {
    private static final String TAG = "MatchList";

    // Menu item ids
    private static final int MENU_ITEM_REFRESH = Menu.FIRST;

    /**
     * The columns we are interested in from the database
     */
    private static final String[] PROJECTION = new String[] {
            Provider.Matches._ID, // 0
            Provider.Matches.DATE, // 1
            Provider.Matches.STATUS, // 2
            Provider.Matches.HOME_TEAM, // 3
            Provider.Matches.AWAY_TEAM, // 4
            Provider.Matches.HOME_TEAM_NAME, // 5
            Provider.Matches.AWAY_TEAM_NAME, // 6
            Provider.Matches.HOME_GOALS, // 7
            Provider.Matches.AWAY_GOALS, // 8
    };

    /** The index of the category column */
	private static final int COLUMN_INDEX_UUID = 0;
    private static final int COLUMN_INDEX_DATE = 1;
    public  static final int COLUMN_INDEX_STATUS = 2;
    private static final int COLUMN_INDEX_HOME_TEAM = 3;
    private static final int COLUMN_INDEX_AWAY_TEAM = 4;
    private static final int COLUMN_INDEX_HOME_TEAM_NAME = 5;
    private static final int COLUMN_INDEX_AWAY_TEAM_NAME = 6;

	private static final int MENU_ITEM_VIEW_MATCH = 0;
	private static final int MENU_ITEM_VIEW_HTEAM = 1;
	private static final int MENU_ITEM_VIEW_ATEAM = 2;


	final Handler uiThreadCallback = new Handler();
    private int addedMatches;

	private MatchListAdapter mAdapter;

	private Cursor mCursor;
	
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);

        // If no data was given in the intent (because we were started
        // as a MAIN activity), then use our default content provider.
        Intent intent = getIntent();
        if (intent.getData() == null) {
            intent.setData(Provider.Matches.CONTENT_URI);
        }

        // Inform the list we provide long click for items
        getListView().setOnCreateContextMenuListener(this);
        
        
        // Perform a managed query. The Activity will handle closing and requerying the cursor
        // when needed.
        mCursor = managedQuery(getIntent().getData(), PROJECTION, null, null,
                Provider.Matches.DEFAULT_SORT_ORDER);

        String[] from = new String[] { Provider.Matches.HOME_TEAM_NAME,
										Provider.Matches.HOME_GOALS,
										Provider.Matches.AWAY_GOALS,
										Provider.Matches.AWAY_TEAM_NAME};
        int[] to = new int[] { R.id.home_team,
								R.id.home_goals,
								R.id.away_goals,
								R.id.away_team};
        // Used to map notes entries from the database to views
        //SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.matchlist_item, mCursor, from, to);
        mAdapter = new MatchListAdapter(this, R.layout.matchlist_item, mCursor, from, to, COLUMN_INDEX_DATE);
        setListAdapter(mAdapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        // This is our one standard application action -- inserting a
        // new note into the list.
        menu.add(0, MENU_ITEM_REFRESH, 0, R.string.menu_refresh)
                .setIcon(R.drawable.refresh);

        // Generate any additional actions that can be performed on the
        // overall list.  In a normal install, there are no additional
        // actions found here, but this allows other applications to extend
        // our menu with their own actions.
        Intent intent = new Intent(null, getIntent().getData());
        intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
        menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, Menu.NONE, Menu.NONE,
                new ComponentName(this, MatchListActivity.class), null, intent, 0, null);

        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MENU_ITEM_REFRESH:
        	Toast.makeText(this, "I wish I could, but you can't currently update on demand. It should be automatic.", Toast.LENGTH_SHORT).show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    protected void onListItemClick(ListView l, View v, int position, long id) {
    	//Log.d(TAG, "List Item Clicked" + getListView().getItemAtPosition(position).getClass().toString());
    	mCursor.moveToPosition(mAdapter.getPosition(position));
        Uri uri = Uri.withAppendedPath(getIntent().getData(), mCursor.getString(COLUMN_INDEX_UUID));
       
        String action = getIntent().getAction();
        if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) {
            // The caller is waiting for us to return a note selected by
            // the user.  The have clicked on one, so return it now.
            setResult(RESULT_OK, new Intent().setData(uri));
            finish();
        } else {
            // Launch activity to view/edit the currently selected item
            startActivity(new Intent(Intent.ACTION_VIEW, uri));
        }
    }

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		AdapterView.AdapterContextMenuInfo info;
        try {
             info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        } catch (ClassCastException e) {
            Log.e(TAG, "bad menuInfo", e);
            return;
        }
        
        if(mCursor.moveToPosition(mAdapter.getPosition(info.position))){
	        
        	String home = mCursor.getString(COLUMN_INDEX_HOME_TEAM_NAME);
        	String away = mCursor.getString(COLUMN_INDEX_AWAY_TEAM_NAME);
	        // Setup the menu header
	        menu.setHeaderTitle(home + " vs " + away);
	
	        // Add a menu item to delete the note
	        menu.add(0, MENU_ITEM_VIEW_MATCH, 0, R.string.menu_view_match);
	        menu.add(0, MENU_ITEM_VIEW_HTEAM, 0, "View " + home);
	        menu.add(0, MENU_ITEM_VIEW_ATEAM, 0, "View " + away);
        }
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info;
        try {
             info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        } catch (ClassCastException e) {
            Log.e(TAG, "bad menuInfo", e);
            return false;
        }
        if(mCursor.moveToPosition(mAdapter.getPosition(info.position))){
        	Uri uri;
	        switch (item.getItemId()) {
	            case MENU_ITEM_VIEW_MATCH:
	                uri = Uri.withAppendedPath(getIntent().getData(), mCursor.getString(COLUMN_INDEX_UUID));
	                startActivity(new Intent(Intent.ACTION_VIEW, uri));
	                return true;
	            case MENU_ITEM_VIEW_HTEAM:
	                uri = Uri.withAppendedPath(Provider.Teams.CONTENT_URI, mCursor.getString(COLUMN_INDEX_HOME_TEAM));
	                startActivity(new Intent(Intent.ACTION_VIEW, uri));
	                return true;
	            case MENU_ITEM_VIEW_ATEAM:
	                uri = Uri.withAppendedPath(Provider.Teams.CONTENT_URI, mCursor.getString(COLUMN_INDEX_AWAY_TEAM));
	                startActivity(new Intent(Intent.ACTION_VIEW, uri));
	                return true;
	        }
        }
        return false;
	}

	// performs update in the ui thread, after background operation is complete
	  final Runnable runInUIThread = new Runnable() {
	    public void run() {
      	Toast.makeText(MatchListActivity.this, "Added " + addedMatches + " matches", Toast.LENGTH_SHORT).show();
	    }
	  };
    

}
